//
//  CalendarView.swift
//  GreenDeal
//
//  Created by Moennig Q on 23/12/2022.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import FSCalendar
class CalendarView: View {
    lazy var disposeBag = DisposeBag()
    fileprivate let gregorian = Calendar(identifier: .gregorian)
    var selectDate = Date()
    var jobsDataObserver: BehaviorRelay<[InstallationListModel]> = BehaviorRelay(value: [])
    var jobsList: [CreateJobStatusModel] = []
    var weatherList: [DayWeatherModel] = []
    var selectDateClosure: (()->Void)?
    var calendarPageClosure: ((Date)->Void)?
    //MARK: - top common view
    let topCommonView = MainTopCommonView()
    let calendar = FSCalendar()
    let switchCalendarModeBtn = UIButton()
    let tableView = TableView()
    //MARK: - 加载失败的view
    lazy var loadFaildView = DatalLoadFaildView()
    //
    var calendarHeightConstraint: Constraint?
    override func setUpView() {
        self.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        //top common view
        topCommonView.showOpertionBtns(showCreateJobBtn: false, showSearchBtn: false)
        topCommonView.topBackImageView.image = nil
        topCommonView.topBackImageView.backgroundColor = UIColor(hexStr: Constant.ThemeColorHexStr)
        self.addSubview(topCommonView)
        topCommonView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //calendar
        calendar.setContentHuggingPriority(.required, for: NSLayoutConstraint.Axis.vertical)
        calendar.setContentCompressionResistancePriority(.required, for: NSLayoutConstraint.Axis.vertical)
        let calendarMargin: CGFloat = 0
        self.addSubview(calendar)
        calendar.snp.makeConstraints { make in
            make.top.equalTo(topCommonView.snp.bottom)
            make.left.equalTo(calendarMargin)
            make.right.equalTo(-calendarMargin)
            self.calendarHeightConstraint = make.height.equalTo(450).constraint
        }
        //
        let preBtnHeight: CGFloat = 40
        let preBtnWidth: CGFloat = (APPConfig.WidthForPortrait - calendarMargin * 2) / 7
        let preBtn = UIButton()
        preBtn.setImage(R.image.calendar_pre_icon(), for: UIControl.State.normal)
        self.addSubview(preBtn)
        preBtn.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalTo(calendar).offset(10)
            make.height.equalTo(preBtnHeight)
            make.width.equalTo(preBtnWidth)
        }
        let nextBtn = UIButton()
        nextBtn.setImage(R.image.calendar_next_icon(), for: UIControl.State.normal)
        self.addSubview(nextBtn)
        nextBtn.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.width.height.equalTo(preBtn)
        }
        //
        switchCalendarModeBtn.drawCorner(byRoundingCorners: [.bottomLeft,.bottomRight])
        switchCalendarModeBtn.backgroundColor = UIColor(hexStr: Constant.ThemeColorHexStr)
        switchCalendarModeBtn.setImage(R.image.caledar_month_to_week_up(), for: UIControl.State.normal)
        self.addSubview(switchCalendarModeBtn)
        switchCalendarModeBtn.snp.makeConstraints { make in
            make.top.equalTo(calendar.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
            
        }
        //tableView
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(switchCalendarModeBtn.snp.bottom)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        loadFaildView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(loadFaildView)
        loadFaildView.snp.makeConstraints { make in
            make.top.equalTo(switchCalendarModeBtn.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        //
        tableView.backgroundColor = .clear
        tableView.register(CalendarJobTableViewCell.self, forCellReuseIdentifier: CalendarJobTableViewCell.reuseCellIdentifier)
        tableView.estimatedRowHeight = 300
        tableView.rowHeight = UITableView.automaticDimension
        //绑定数据源，显示数据
        jobsDataObserver.bind(to: tableView.rx.items(cellIdentifier: CalendarJobTableViewCell.reuseCellIdentifier,cellType: CalendarJobTableViewCell.self)){(row, model, cell) in
            cell.setData(model)
        }.disposed(by: self.disposeBag)
        //
        calendar.dataSource = self
        calendar.delegate = self
        calendar.backgroundColor = UIColor(hexStr: Constant.ThemeColorHexStr)
        calendar.allowsMultipleSelection = false//不允许多选
        calendar.scope = .month//选择月模式
//        calendar.appearance.borderRadius = 0.3//选中背景没有圆角，显示为正方形的背景
        calendar.placeholderType = .fillHeadTail//首位都接上
        calendar.firstWeekday = 1//周的第一天从sunday开始，2：表示从Monday开始
        //header
        calendar.headerHeight = 60//Header的高度
        calendar.appearance.headerDateFormat = "MMMM yyyy"
        calendar.appearance.headerTitleFont = R.font.interSemiBold(size: 17)//March 2023的字体
        calendar.appearance.headerTitleColor = UIColor.white//月份的显示颜色
        calendar.appearance.headerTitleAlignment = .center//March 2023左靠齐
        calendar.appearance.headerSeparatorColor = .clear//March 2023下边的分割线颜色
        calendar.appearance.headerMinimumDissolvedAlpha = 0//March 2023左右两边的月份颜色透明度为0，即不显示
        //calendar.pagingEnabled设置为true，下边两行代码有效；否则失效
//        calendar.appearance.headerMinimumDissolvedAlpha = 1//
//        calendar.calendarHeaderView.drawCorner(byRoundingCorners: [.topLeft,.topRight],backColorHexStr: "#005D2D1A")//设置header（March 2023）的圆角和背景颜色
        calendar.scrollDirection = .horizontal//垂直滚动
        calendar.pagingEnabled = true//翻页,翻页设置为false，
         //weekday
        calendar.rowHeight = 50
        calendar.weekdayHeight = 40
        calendar.appearance.caseOptions = .weekdayUsesUpperCase//星期(MON)三个字母大写
        calendar.appearance.weekdayFont = R.font.interRegular(size: 13)//周标题的字体
        calendar.appearance.weekdayTextColor = UIColor(hexStr: "#FFFFFF99")//周标题字体颜色
        //day
        calendar.appearance.titleFont = R.font.interRegular(size: 16)//日期的字体
//        calendar.appearance.titleDefaultColor = UIColor.white//日期的没选中的颜色
        //颜色
//        calendar.appearance.selectionColor = UIColor(hexStr: "#FFFFFF").withAlphaComponent(0.6)//UIColor(hexStr: "#9FACBE80")//选中背景的颜色
        calendar.appearance.todayColor = UIColor.clear//今天默认的背景颜色
        calendar.appearance.todaySelectionColor = .clear//UIColor(hexStr: "#FFFFFF").withAlphaComponent(0.6)//今天的选中的背景颜色//
        //自定义FScalendar cell
        calendar.register(DIYFSCalendarCellForCalendar.self, forCellReuseIdentifier: DIYFSCalendarCellForCalendar.reuseCellIdentifier)
        //切换月或week
        switchCalendarModeBtn.addTarget(self, action: #selector(switchCalendarModeBtnClick), for: UIControl.Event.touchUpInside)
        //切换日历上一个月或上一周
        preBtn.addTarget(self, action: #selector(preBtnClick), for: UIControl.Event.touchUpInside)
        nextBtn.addTarget(self, action: #selector(nextBtnClick), for: UIControl.Event.touchUpInside)
        //
        loadFaildView.isHidden = true
    }
    //MARK: - 切换日历上一个月或上一周
    @objc func preBtnClick(){
        self.getPreOrNextDate(-1)
    }
    //MARK: - 切换日历下一个月或下一周
    @objc func nextBtnClick(){
        self.getPreOrNextDate(1)
    }
    //MARK: - 获取上个月（上一周）下个月（下一周）的日期
    private func getPreOrNextDate(_ count: Int){
        self.dealSelectDateForPageChanged(count)
        self.calendar.setCurrentPage(self.selectDate, animated: true)//自动调用calendarCurrentPageDidChange
    }
    //
    private func dealSelectDateForPageChanged(_ count: Int){
        var nextPage: Date
        if self.calendar.scope == .month {
            nextPage = DateUtil().getServeralYearOfToday(date: self.selectDate,month: count)
        }else{
            nextPage = DateUtil().getServeralYearOfToday(date: self.selectDate,week: count)
        }
        self.selectDate = nextPage
    }
    //MARK: - 切换日历的周或月的mode
    @objc func switchCalendarModeBtnClick(){
        if self.calendar.scope == .week {
            self.calendar.scope = .month
            self.calendar.setScope(.month, animated: true)
            self.calendarHeightConstraint?.update(offset: 450)
            self.switchCalendarModeBtn.setImage(R.image.caledar_month_to_week_up(), for: UIControl.State.normal)
        }else{
            self.calendar.scope = .week
            self.calendar.setScope(.week, animated: true)
            self.calendarHeightConstraint?.update(offset: 165)
            self.switchCalendarModeBtn.setImage(R.image.caledar_week_to_month_down(), for: UIControl.State.normal)
        }
    }
    func showDetailView(){
        self.tableView.isHidden = false
        self.loadFaildView.isHidden = true
    }
    //加载失败的view
    func showFaildView(){
        self.tableView.isHidden = true
        self.loadFaildView.isHidden = false
    }

}
extension CalendarView: FSCalendarDataSource, FSCalendarDelegate , FSCalendarDelegateAppearance {
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        self.selectDate = date
        if monthPosition == .current {//选择当月的日期
            self.selectDateClosure?()
            self.configureVisibleCells()
        }else{//选在上个月下个月的日期
            self.calendar.select(self.selectDate, scrollToDate: true)
        }
    }
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        if self.calendar.scope == .month{//month
            let currentPageDateMonthStr = DateUtil().getDatetimeStr(self.calendar.currentPage, format: "yyyy-MM",timeZone: TimeZone.current)
            let selectDateMonthStr = DateUtil().getDatetimeStr(self.selectDate, format: "yyyy-MM",timeZone: TimeZone.current)
            if currentPageDateMonthStr != selectDateMonthStr{//不一致，表示是左右滑动的翻页，要特别处理select date，否则翻页后不会自动选择到日期
                if calendar.currentPage.timeIntervalSince1970 < self.selectDate.timeIntervalSince1970{//往前翻页
                    self.dealSelectDateForPageChanged(-1)
                }else if calendar.currentPage.timeIntervalSince1970 > self.selectDate.timeIntervalSince1970{//往后翻页
                    self.dealSelectDateForPageChanged(1)
                }
            }
        }else if self.calendar.scope == .week{//week
            if let currentPageDateWeekOfYear = Calendar.current.dateComponents([.weekOfYear], from: self.calendar.currentPage).weekOfYear, let selectDateWeekOfYear = Calendar.current.dateComponents([.weekOfYear], from: self.selectDate).weekOfYear{
                if currentPageDateWeekOfYear < selectDateWeekOfYear{//往前翻页
                    self.dealSelectDateForPageChanged(-1)
                }else if  currentPageDateWeekOfYear > selectDateWeekOfYear{//往后翻页
                    self.dealSelectDateForPageChanged(1)
                }
            }
            
        }
        self.calendarPageClosure?(self.selectDate)
        self.configureVisibleCells()
        
    }
//    func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
//        self.calendarHeightConstraint?.update(offset: CGRectGetHeight(bounds))
        
//        self.calendarHeight.constant = CGRectGetHeight(bounds);
//        [self.view layoutIfNeeded];
//        self.preferredContentSize = CGSizeMake(calendar.frame.size.width, self.calendarHeight.constant);
//    }
    //MARK: -
    func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell = calendar.dequeueReusableCell(withIdentifier: DIYFSCalendarCellForCalendar.reuseCellIdentifier, for: date, at: position)
        return cell
    }
    func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
        self.configure(cell: cell, for: date, at: position)
    }
    // MARK: - Private functions
    private func configureVisibleCells() {
        calendar.visibleCells().forEach { (cell) in
            let date = calendar.date(for: cell)
            let position = calendar.monthPosition(for: cell)
            self.configure(cell: cell, for: date!, at: position)
        }
    }
    private func configure(cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
        let diyCell = (cell as! DIYFSCalendarCellForCalendar)
        //1.选中时，自定义背景layer的显示
        let selectDate = DateUtil().getDatetimeStr(self.selectDate,format: "yyyy-MM-dd")
        let currentDate = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
        
        if selectDate == currentDate {//选中时
            diyCell.dateLabel.textColor = UIColor(hexStr: Constant.ThemeColorHexStr)
            diyCell.selectBackLayer.fillColor = UIColor(hexStr: "#FFFFFF99").cgColor
            diyCell.selectBackLayer.isHidden = false
        }else{//选中时，非今天的颜色
            //不在当月的日期颜色不一样
            let monthOfSelectDate = DateUtil().getDatetimeStr(calendar.currentPage,format: "yyyy-MM")
            let monthOfCurrentDateMonth = DateUtil().getDatetimeStr(date,format: "yyyy-MM")
            if monthOfSelectDate != monthOfCurrentDateMonth{
                diyCell.dateLabel.textColor = UIColor(hexStr: "#FFFFFF66")
            }else{
                diyCell.dateLabel.textColor = .white
            }
            
            diyCell.selectBackLayer.fillColor = UIColor.clear.cgColor
            diyCell.selectBackLayer.isHidden = true
        }
        diyCell.dateLabel.text = DateUtil().getDatetimeStr(date,format: "dd")
        
        let jobCnt = self.jobsList.filter({$0.install_date == currentDate}).count
        if jobCnt > 0{
            diyCell.jobCntLabel.text = "\(jobCnt)"
            diyCell.jobCntLabel.isHidden = false
        }else{
            diyCell.jobCntLabel.isHidden = true
        }
    }
//    //MARK: -选中时日期的颜色
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleSelectionColorFor date: Date) -> UIColor? {
//        return UIColor(hexStr: Constant.ThemeColorHexStr)
//    }
//    //MARK: -有event的date，显示几个点
//    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
//        return 1
//    }
//    //MARK: - 选中时event的的颜色，分为not completed和completed两种
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventSelectionColorsFor date: Date) -> [UIColor]? {
//        return self.setEventColor(date)
//    }
//    //MARK: - event绿点的偏移量
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventOffsetFor date: Date) -> CGPoint {
//        return CGPoint(x: 0, y: 2)
//    }
//    //MARK: - event的默认的颜色，分为not completed和completed两种
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? {
//        return self.setEventColor(date)
//    }
    
    //MARK: - 设置event的color
//    private func setEventColor(_ date: Date) -> [UIColor]? {
//        let dateStr = DateUtil().getDatetimeStr(date,format: "yyyy-MM-dd")
//        if self.completedList.contains(dateStr) {
//            return [UIColor(hexStr: Constant.ThemeColorHexStr)]
//        }
//
//        if self.notCompletedList.contains(dateStr){
//            return [UIColor(hexStr: "#A2A2A2")]
//        }
//        return nil
//    }
}
